<template>
  <div class="completed-orders-page">
    <van-list v-model="loading" :finished="finished" finished-text="没有更多订单了">
      <!-- 遍历每个订单 -->
      <van-card v-for="(order, index) in orders" :key="index" :title="'第' + (index + 1) + '个订单'" :price="order.total_amount" v-show="order.order_status===2">
        <template #tags>
          <van-tag type="success">
            已完成
          </van-tag>
          <div class="goods-list">
            <div v-for="(item, itemIndex) in order.items" :key="itemIndex" class="goods-item" @click="router.push(`/goodsDetail/${item.goods_id}`)">
              <img :src="`http://127.0.0.1:8360/${item.goods.picture}`" alt="商品图片" class="goods-image" />
              <div class="goods-info">
                <div class="goods-name">{{ item.goods.name }}</div>
                <div class="goods-price">￥{{ item.goods.price }}</div>
                <div class="goods-quantity">数量: {{ item.quantity }}</div>
              </div>
            </div>
          </div>
        </template>

        <template #footer>
          <div class="actions">
            <van-button type="default" size="small" @click="viewLogistics(order.id)">
              查看物流
            </van-button>
          </div>
        </template>
      </van-card>
    </van-list>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import useOrder from '@/stores/order.js';

const { getOrdersInfo, getFinishedNum } = useOrder();
const orders = ref([]);
const loading = ref(false);
const finished = ref(false);
const router = useRouter();

onMounted(async () => {
  await loadOrders();
});

// 加载已完成订单列表
const loadOrders = async () => {
  orders.value = await getOrdersInfo();
  if (getFinishedNum() === 0) {
    finished.value = true; // 如果没有更多订单了，标记为已完成
  }
};

// 查看物流
const viewLogistics = async () => {
  showToast('已经送到了，孩子');
};

</script>

<style scoped>
.completed-orders-page {
  padding: 20px;
  background-color: #fff;
}

.goods-list {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
}

.goods-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.goods-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  margin-right: 10px;
}

.goods-info {
  flex-grow: 1;
}

.goods-name {
  font-weight: bold;
}

.goods-price {
  color: #f56c6c;
}

.goods-quantity {
  font-size: 12px;
  color: #888;
}

.actions {
  display: flex;
  justify-content: flex-end;
}

.van-button {
  width: 120px;
}

.empty-orders {
  text-align: center;
  margin-top: 50px;
}
</style>
